<template>
  <div class="navbar">
    <div class="navbar-left">
      <span class="current-page-item" index="current_page">{{
        tabStore.currentPageName }}</span>
    </div>

    <div class="navbar-center">
    
      <!-- 搜索框 -->
      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索文章..."
          prefix-icon="Search"
          clearable
          class="search-input"
          @keyup.enter="handleSearch"
        >
        </el-input>
      </div>

      <el-menu v-if="menuConfig.length" mode="horizontal" :default-active="activeIndex" class="el-menu-center" @select="handleSelect"
        :background-color="isDark ? '#1a1a1a' : '#ffffff'" :text-color="isDark ? '#ffffff' : '#303133'"
        :active-text-color="isDark ? '#409eff' : '#409eff'"
        :class="{ 'no-active-style': tabStore.currentPageName != 'Home' }">
        <!-- 首页菜单项 -->
        <el-menu-item index="home" @click="handleTabChange('Home', 'home')">首页</el-menu-item>
        <el-menu-item index="my" @click="handleTabChange('Home', 'my')">我的</el-menu-item>

        <!-- 遍历一级菜单 -->
        <template v-for="item in menuConfig" :key="item.id">
          <!-- 如果有子菜单，使用sub-menu并递归渲染 -->
          <el-sub-menu v-if="item.child_category_list?.length" :index="String(item.id)">
            <template #title>{{ item.slug }}</template>
            <MenuTree :items="item.child_category_list" />
          </el-sub-menu>
          <!-- 没有子菜单，直接显示为menu-item -->
          <el-menu-item v-else :index="String(item.id)" @click="tabStore.setCategory(item.id)">
            {{ item.slug }}
          </el-menu-item>
        </template>
      </el-menu>
    </div>

    <div class="navbar-right">
      <!-- 添加刷新按钮 -->
      <el-button 
        type="text" 
        icon="Message" 
        class="chat-button"
        @click="goToChatRoom"
        :style="{ color: isDark ? '#ffffff' : '#303133' }"
      >
        聊天室
      </el-button>

      <!-- 分隔符 -->
      <div class="navbar-separator"></div>

      <ThemeSwitch />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import ThemeSwitch from './ThemeSwitch.vue'
import MenuTree from './MenuTree.vue'
import router from '../router'
import { useRoute } from 'vue-router'
import { useTabStore } from '../stores/tab.js';
import categoryApi from '../api/category.js';

const tabStore = useTabStore();
const searchKeyword = ref('');

const goToChatRoom = () => {
  router.push({ name: 'ChatRoom' })
}

// 添加防抖函数(一般是监控是输入框的变化需用到的)
const debounce = (fn, delay = 300) => {
  let timer = null;
  return (...args) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  }
}

const handleSearch = () => {
  //无论在哪个页面，都跳转到首页然后触发home页面的接口
  // if (searchKeyword.value.trim()){
    // console.log(searchKeyword.value);
  tabStore.setSearchKeyword(searchKeyword.value)
    // router.push({ name: 'Home', query: { tab: 'home', keyword: searchKeyword.value } })
  // } else {
    // 如果是空的情况触发原来的查询

  // }
}

function handleTabChange(pageName, tab) {
  // 先初始化数据
  tabStore.init_data()
  router.push({ name: pageName, query: { tab: tab } })
  tabStore.setTab(tab)
}

const emit = defineEmits(['changeTab'])

const route = useRoute()
const activeIndex = ref('')
const isDark = computed(() => document.documentElement.classList.contains('dark-theme'))

const currentPageName = ref('')

const getCurrentPageName = () => {
  console.log("当前页面", route.name);

  if (route.name != 'Home') {
    currentPageName.value = route.name
    activeIndex.value = "current_page"
  }
}

const menuConfig = ref([]);

// 添加手动刷新函数
const manualRefreshMenu = async () => {
  console.log('手动触发菜单刷新')
  
  // 触发resize事件
  window.dispatchEvent(new Event('resize'))
  
  // 使用nextTick确保DOM更新
  await nextTick()
  
  // 多层次触发
  setTimeout(() => {
    window.dispatchEvent(new Event('resize'))
  }, 100)
  
  setTimeout(() => {
    window.dispatchEvent(new Event('resize'))
  }, 300)
  
  // 尝试触发Element Plus内部事件
  const menuElement = document.querySelector('.el-menu-center')
  if (menuElement) {
    // 触发Element Plus可能监听的事件
    const updateEvent = new Event('update')
    menuElement.dispatchEvent(updateEvent)
    
    // 强制重排
    const originalDisplay = menuElement.style.display
    menuElement.style.display = 'none'
    void menuElement.offsetHeight
    menuElement.style.display = originalDisplay
  }
  
  console.log('手动刷新完成')
}

const getAllCategory = async () => {
  const res = await categoryApi.GetAllCategoryList()
  console.log(res);
  
  if (res.code == 0) {
    menuConfig.value = res.data

    // 添加多次nextTick和延迟，确保DOM完全更新
    // await nextTick()
    
    // // 短暂延迟后再次触发更新
    // setTimeout(async () => {
    //   await nextTick()
    //   window.dispatchEvent(new Event('resize'))
    // }, 100)
    
    // // 再延迟一点时间再次触发，确保所有层级都能正确渲染
    // setTimeout(async () => {
    //   await nextTick()
    //   window.dispatchEvent(new Event('resize'))
    // }, 300)
  }
  await nextTick()

}
// 菜单配置
// const menuConfig = [
//   {
//     name: 'backend', label: '后端', children: [
//       { name: 'java', label: 'Java' },
//       { name: 'python', label: 'Python' },
//       { name: 'go', label: 'Go' }
//     ]
//   },
//   {
//     name: 'frontend', label: '前端', children: [
//       { name: 'vue', label: 'Vue' },
//       { name: 'react', label: 'React' }
//     ]
//   },
//   {
//     name: 'database', label: '数据库', children: [
//       { name: 'mysql', label: 'MySQL' },
//       { name: 'postgres', label: 'Postgres' },
//       {
//         name: 'nosql', label: 'NoSQL', children: [
//           { name: 'mongo', label: 'MongoDB' },
//           { name: 'redis', label: 'Redis' }
//         ]
//       }
//     ]
//   }
// ]
// const toHomePage = () => {
//   router.push({ name: 'Home', query: { tab: 'home' } })
//   emit('changeTab', 'home')
// }

// const toMyPage = () => {
//   router.push({ name: 'Home', query: { tab: 'my' } })
//   emit('changeTab', 'my')
// }

// 过滤出有效的菜单项

const handleSelect = (key) => {
  activeIndex.value = key
}

const fetchTab = () => {
  if (route.query.tab) {
    activeIndex.value = route.query.tab;
  };
}

watch(() => tabStore.currentPageName, () => {
  getCurrentPageName();
})

onMounted(() => {
  // getCurrentPageName()
  fetchTab();
  getAllCategory();
})
</script>

<style scoped>
.navbar {
  display: flex;
  align-items: center;
  padding: 0 20px;
  background: var(--header-bg);
  border-bottom: 1px solid var(--border-color);
  position: sticky;
  top: 0;
  z-index: 100;
  width: 100%;
  box-sizing: border-box;
  /* overflow-x: hidden; */
}

/* 搜索框样式 */
.search-container {
  margin-right: 20px;
  min-width: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-input {
  width: 100%;
  max-width: 220px;
  height: 36px;
  border-radius: 18px;
}

.current-page-item {
  font-weight: bold;
  color: #409eff;
  /* 选中时的高亮色，与el-menu一致 */
  background: #ecf5ff;
  /* 可选，和el-menu-item选中时一致 */
  border-radius: 4px;
  padding: 0 12px;
  font-size: 16px;
  height: 40px;
  display: flex;
  align-items: center;
}


.navbar-left {
  min-width: 120px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-shrink: 0;
}

.navbar-center {
  flex: 1;
  display: flex;
  justify-content: center;
  min-width: 0;
  overflow-x: visible;
  /* -webkit-overflow-scrolling: touch; */
}


.navbar-right {
  min-width: 140px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex-shrink: 0;
  gap: 10px; /* 添加间隙使按钮间距更合理 */
}
/* 聊天室按钮样式 */
.chat-button {
  background-color: #409eff; /* 使用蓝色背景使其突出 */
  color: white !important;
  border-radius: 4px;
  padding: 6px 12px !important;
  transition: all 0.3s;
}
.chat-button:hover {
  background-color: #66b1ff !important;
  color: white !important;
}
/* 深色主题下的聊天室按钮样式 */
.dark-theme .chat-button {
  background-color: #66b1ff; /* 稍微浅一点的蓝色，适应深色主题 */
  color: white !important;
}

.dark-theme .chat-button:hover {
  background-color: #99ccff !important;
}

.navbar-separator {
  width: 1px;
  height: 20px;
  background-color: var(--border-color);
  margin: 0 5px;
}

.dark-theme .navbar-separator {
  background-color: #333;
}

.el-menu {
  flex: 1;
  border: none !important;
  background-color: transparent !important;
    min-width: 0;

}

:deep(.el-menu--horizontal) {
  border-bottom: none !important;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  white-space: nowrap;
}
:deep(.el-menu--horizontal::-webkit-scrollbar) {
  display: none;
}

/* 确保弹出菜单样式正确 */
:deep(.el-menu--popup-container) {
  background-color: var(--card-bg) !important;
}

:deep(.el-menu--popup) {
  background-color: var(--card-bg) !important;
  border: 1px solid var(--border-color) !important;
}

:deep(.el-menu--popup .el-menu-item) {
  color: var(--text-primary) !important;
}

:deep(.el-menu--popup .el-menu-item:hover) {
  background-color: var(--tag-bg) !important;
}

:deep(.el-sub-menu__title) {
  color: var(--text-primary) !important;
}

:deep(.el-sub-menu__icon-arrow) {
  color: var(--text-primary) !important;
}

/* 只有 no-active-style 时才取消高亮 */
:deep(.no-active-style .el-menu-item.is-active) {
  background-color: transparent !important;
  color: inherit !important;
  box-shadow: none !important;
}
/* 刷新按钮样式 */
.refresh-button {
  background-color: #67c23a; /* 使用绿色背景 */
  color: white !important;
  border-radius: 4px;
  padding: 6px 12px !important;
  transition: all 0.3s;
  margin-right: 10px;
}
.refresh-button:hover {
  background-color: #85ce61 !important;
  color: white !important;
}
/* 深色主题下的刷新按钮样式 */
.dark-theme .refresh-button {
  background-color: #85ce61; /* 稍微浅一点的绿色，适应深色主题 */
  color: white !important;
}

.dark-theme .refresh-button:hover {
  background-color: #95de73 !important;
}
</style>